package com.sfh.dog.util;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.DisplayMetrics;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.LoadedFrom;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.sfh.dog.R;

public class PhotoUtil
{
	/** post 参数 文件 */
	public static final String FILE = "file";

	
	/** 拍照 */
	public static final int SELECT_PICTURE_FROM_CAMERA = 0x2006;

	/** 图库 */
	public static final int SELECT_PICTURE_FROM_FILE = 0x2007;

	/***
	 * 打开拍照
	 * 
	 * @param context
	 * @param imageCaptureUri
	 */
	public static String startActivityNowPic(Context context)
	{
		Intent intent = new Intent();
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

		String newPicFile = System.currentTimeMillis() + ".jpg";
		String outPath = new File(Environment.getExternalStorageDirectory(),
				newPicFile).getPath();
		File outFile = new File(outPath);
		Uri outuri = Uri.fromFile(outFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
		((Activity) context).startActivityForResult(intent,
				SELECT_PICTURE_FROM_CAMERA);
		return outFile.toString();
	}

	public static File onActivityResultNowPhoto(Intent data,
			String mCameraFileName)
	{
		Uri uri = null;
		if (data != null)
		{
			uri = data.getData();
		}
		if (uri == null && mCameraFileName != null)
		{
			uri = Uri.fromFile(new File(mCameraFileName));
		}
		File file = new File(mCameraFileName);

		if (uri != null)
		{
			return file;
		}
		return null;
	}

	/***
	 * 打开图库
	 * 
	 * @param context
	 */
	public static void startActivityLib(Context context)
	{
		// 图库
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		Intent wrapi = Intent.createChooser(intent, "选择图片");
		((Activity) context).startActivityForResult(wrapi,
				SELECT_PICTURE_FROM_FILE);
	}

	public interface IPhoto
	{
		public void getPhoto(String path);
	}

	/***
	 * 异步获取相册图片
	 */
	public static class AsySearchPhoto extends AsyncTask<Uri, Void, String>
	{
		private Context context;
		private IPhoto mPhoto;

		public AsySearchPhoto(Context context, IPhoto photo)
		{
			super();
			this.context = context;
			this.mPhoto = photo;
		}

		@Override
		protected String doInBackground(Uri... params)
		{
			String[] projection = { MediaColumns.DATA };
			Cursor cursor = context.getContentResolver().query(params[0],
					projection, null, null, null);
			String path = null;
			if (cursor != null)
			{
				int column_index = cursor
						.getColumnIndexOrThrow(MediaColumns.DATA);
				cursor.moveToFirst();
				path = cursor.getString(column_index);
				try
				{
					// 4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
					if (Integer.parseInt(Build.VERSION.SDK) < 14)
					{
						cursor.close();
					}
				} catch (Exception e)
				{
				}
			}

			return path;
		}

		@Override
		protected void onPostExecute(String result)
		{
			if (result != null && !"".equals(result) && mPhoto != null)
			{
				// 返回选择图片地址
				mPhoto.getPhoto(result);
			}
		}
	}

	/**
	 * 圆形图片
	 * 
	 * @param arg
	 *            [0] color 边框颜色 传入-1显示白色，其它的传入具体的颜色 arg[1] sideLength
	 *            ImageView边长，请换算成像素再传进来
	 * @return
	 */
	public static DisplayImageOptions getCircleFrameImageOption(int... args)
	{
		if ((args.length != 1) && (args.length != 2))
		{
			throw new IllegalArgumentException(
					"请传入一个color参数，或者一个color，一个sideLength参数");
		}
		RoundFrameDisplayer displayer = null;
		if (args.length == 1)
		{
			displayer = new RoundFrameDisplayer(args[0]);
		} else
		{
			displayer = new RoundFrameDisplayer(args[0], args[1]);
		}
		Options mOptions = new Options();
		mOptions.inSampleSize = 18;
		DisplayImageOptions circleOptions = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.a_reward_s)
				.showImageOnFail(R.drawable.a_reward_s).cacheInMemory(true)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
				.decodingOptions(mOptions).bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(displayer).build();
		return circleOptions;
	}

	/**
	 * 圆形头像，边框，有颜色
	 */
	public static class RoundFrameDisplayer implements BitmapDisplayer
	{

		private int mSideColor = -1;

		private int mSizeLength = -1;

		private static int mStrokeWidth=1;

		public RoundFrameDisplayer()
		{
			init();
		}

		/**
		 * 在控件已经加载完毕可以调用此构造，否则请使用两个参数的构造
		 * 
		 * @param sideColor
		 */
		public RoundFrameDisplayer(int sideColor)
		{
			this.mSideColor = sideColor;
			init();
		}

		/**
		 * 主动将ImageView的边长传进来
		 * 
		 * @param sideColor
		 * @param sideLength
		 */
		public RoundFrameDisplayer(int sideColor, int sideLength)
		{
			this(sideColor);
			this.mSizeLength = sideLength;
			init();
		}

		private void init()
		{
			if (mStrokeWidth == 0)
			{
				DisplayMetrics dm = new DisplayMetrics();
				//MyApplication.getDefaultDisplay().getMetrics(dm);
			//	mStrokeWidth = (int) (5f * dm.density);
			}
		}

		@Override
		public void display(Bitmap bitmap, ImageAware imageView, LoadedFrom arg2)
		{
			final int bW = bitmap.getWidth();
			final int bH = bitmap.getHeight();

			int size = mSizeLength;

			if (-1 == mSizeLength)
			{
				size = Math.min(imageView.getWidth(), imageView.getHeight());

				// 如果没有加载到控件的宽高，则用bitmap的宽高来计算
				if (size == 0)
				{
					size = Math.max(bW, bH);
				}
			}

			Bitmap out = Bitmap.createBitmap(size, size, Config.ARGB_8888);
			int centerX = size / 2;
			int centerY = centerX;
			Canvas canvas = new Canvas(out);

			final int sidecolor = mSideColor == -1 ? 0xffffffff : mSideColor;
			final Paint paint = new Paint();

			final float strokeWidth = mStrokeWidth;

			paint.setAntiAlias(true);
			canvas.drawARGB(0, 0, 0, 0);
			paint.setColor(sidecolor);
			canvas.drawCircle(centerX, centerY, size / 2, paint);

			paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

			canvas.save();
			float ratio = (float) size / (float) Math.min(bH, bW);
			canvas.scale(ratio, ratio, centerX, centerY);
			canvas.drawBitmap(bitmap, (size - bW) / 2, (size - bH) / 2, paint);
			canvas.restore();

			paint.setStyle(Style.STROKE);
			paint.setStrokeWidth(strokeWidth);
			canvas.drawCircle(centerX, centerY, size / 2, paint);

			imageView.setImageBitmap(out);

		}

	}

}
